package com.forest.core.etx

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.res.AssetManager
import android.graphics.Bitmap
import android.media.MediaScannerConnection
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import androidx.core.content.FileProvider
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.nio.charset.Charset
import kotlin.concurrent.thread


fun AssetManager.fileAsString(subdirectory: String, filename: String): String {
    return open("$subdirectory/$filename").use {
        it.readBytes().toString(Charset.defaultCharset())
    }
}

fun Context.getCacheFile(uniqueName: String): File {
    var cachePath: String? = null
    if (Environment.MEDIA_MOUNTED == Environment
            .getExternalStorageState()
    ) {
        val cacheDir = externalCacheDir
        if (cacheDir != null) {
            cachePath = cacheDir.path
        }
    } else {
        cachePath = cacheDir.path
    }
    if (cachePath == null) {
        cachePath = Environment.getExternalStorageDirectory().absolutePath
    }
    val file = File(cachePath + File.separator + uniqueName)
    if (!file.exists()) {
        file.mkdirs()
    }
    return file
}

fun Context.saveFile(bitmap: Bitmap, saveFile: File, isMediaStore: Boolean = false): File? {
    return try {
        val bos = saveFile.outputStream()
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos)
        bos.flush()
        bos.close()
        if (isMediaStore) {
            MediaStore.Images.Media.insertImage(
                contentResolver,
                bitmap, saveFile.path, null
            )
            sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, getFileUri(saveFile)))
        }
        saveFile
    } catch (e: FileNotFoundException) {
        null
    }
}

fun saveBitmap(dir: String, bitmap: Bitmap): String {
    val path = "$dir${File.separator}${System.currentTimeMillis()}.jpg"
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, FileOutputStream(path))
    return path
}

fun saveImageList(activity: Activity, imageList: List<Bitmap>, success: () -> Unit = {}) {
    activity.run {
        runOnUiThread {
            thread(true) {
                // 保存图片
                val dir = getTmpFileDir()
                val paths = imageList.reversed().map { saveBitmap(dir, it) }.toTypedArray()
                val mimeTypes = Array(paths.size) { "image/*" }
                // 扫描图片
                val uriList = mutableListOf<Uri>()
                MediaScannerConnection.scanFile(activity, paths, mimeTypes) { _, uri ->
                    uriList.add(uri)
                    if (uriList.size >= paths.size) {
                        runOnUiThread {
                            success()
                        }
                    }
                }
            }
        }
    }
}


fun Context.saveFile(buffer: ByteArray, saveFile: File): File? {
    return try {
        saveFile.outputStream().apply {
            write(buffer)
            close()
        }
        saveFile
    } catch (e: FileNotFoundException) {
        null
    }
}

fun Context.getTmpFileDir(): String {
    val parent = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
    val child = "$packageName${File.separator}shareTemp"
    return File(parent, child)
        .run {
            if (!exists()) {
                mkdirs()
            }
            absolutePath
        }
}

fun Context.clearTmpFile() {
    val fileDir = File(getTmpFileDir())
    // 通知相册删除图片。
    fileDir.listFiles().forEach {
        contentResolver.delete(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            MediaStore.Images.Media.DATA + "=?",
            arrayOf(it.absolutePath)
        )
    }
    clearDir(fileDir)
}

fun Context.getFileUri(file: File): Uri {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        FileProvider.getUriForFile(this, "$packageName.fileProvider", file)
    } else {
        Uri.fromFile(file)
    }
}

fun clearDir(dir: File?): Boolean {
    if (dir == null) return false
    // dir doesn't exist then return true
    if (!dir.exists()) return true
    // dir isn't a directory then return false
    if (!dir.isDirectory) return false
    val files = dir.listFiles()
    if (files != null && files.isNotEmpty()) {
        for (file in files) {
            if (file.isFile) {
                if (!file.delete()) return false
            } else if (file.isDirectory) {
                if (!deleteDir(file)) return false
            }
        }
    }
    return true
}

fun deleteDir(dir: File?): Boolean {
    if (dir == null) return false
    // dir doesn't exist then return true
    if (!dir.exists()) return true
    // dir isn't a directory then return false
    if (!dir.isDirectory) return false
    val files = dir.listFiles()
    if (files != null && files.isNotEmpty()) {
        for (file in files) {
            if (file.isFile) {
                if (!file.delete()) return false
            } else if (file.isDirectory) {
                if (!deleteDir(file)) return false
            }
        }
    }
    return dir.delete()
}

//删除文件夹和文件夹里面的文件
fun deleteDir(pPath: String) {
    if (pPath.isNullOrBlank() || "null" == pPath) {
        return
    }
    val dir = File(pPath)
    deleteDirWithFile(dir)
}

fun deleteDirWithFile(dir: File?) {
    if (dir == null || !dir.exists() || !dir.isDirectory) {
        return
    }
    for (file in dir.listFiles()) {
        if (file.isFile) {
            file.delete() // 删除所有文件
        } else if (file.isDirectory) {
            deleteDirWithFile(file) // 递规的方式删除文件夹
        }
    }
    dir.delete()// 删除目录本身
}



